/* 注册全局组件 */
// import XtxSkeleton from './xtx-skeleton.vue'
// import XtxCarousel from './xtx-carousel.vue'
// import XtxMore from './xtx-more.vue'
// import XtxBread from './xtx-bread.vue'
// import XtxBreadItem from './xtx-bread-item.vue'

import { useIntersectionObserver } from '@vueuse/core'

import defaultImg from '@/assets/images/200.png' // 默认图

import xtxMessage from './Message.js'

const importFn = require.context('./', false, /\.vue$/) // 自动注册组件

/* 注册自定义指令 */
const defineDirective = app => {
  /* 图片懒加载 */
  app.directive('src', {
    mounted (el, { value }) {
      // 开启检测懒加载
      const { stop } = useIntersectionObserver(
        el,
        // isIntersecting - 节点显示状态
        ([{ isIntersecting }], observerElement) => {
          if (isIntersecting) {
            stop() // 停止检测
            el.src = value // 开始加载图片
            el.onerror = () => (el.src = defaultImg) // 错误图
          }
        },
        { threshold: 0 }
      )
    }
  })
  /* 消息弹窗 */
  app.config.globalProperties.$message = xtxMessage
}

export default {
  install (app) {
    /* 自动注册组件 */
    importFn.keys().map(path => {
      const components = importFn(path).default
      app.component(components.name, components)
    })
    // app.component(XtxSkeleton.name, XtxSkeleton) // 骨架屏
    // app.component(XtxCarousel.name, XtxCarousel) // 轮播图
    // app.component(XtxMore.name, XtxMore) // 轮播图
    // app.component(XtxBread.name, XtxBread) // 面包屑
    // app.component(XtxBreadItem.name, XtxBreadItem)

    /* 自定义指令 */
    defineDirective(app)
  }
}
